package com.jeeplus.modules.monitor.entity;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import com.jeeplus.common.websocket.service.system.SystemInfoSocketHandler;

/**
 * 定时任务工作类
 * @author ty
 * @date 2015年1月13日
 */
@DisallowConcurrentExecution
public abstract class Task implements Job {

	private static final String APPLICATION_CONTEXT_KEY = "applicationContextKey";

	ApplicationContext cxt = null;

	/**
	 * 系统通知bean
	 * @return
	 */
	@Bean
	public SystemInfoSocketHandler systemInfoSocketHandler() {
		return new SystemInfoSocketHandler();
	}

	public void execute(JobExecutionContext context) throws JobExecutionException {
		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		try {
			cxt = this.getApplicationContext(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (scheduleJob.getIsInfo().equals("1")) {

			systemInfoSocketHandler().sendMessageToUser("admin",
					"任务名称 = [" + scheduleJob.getName() + "]" + " 在 " + dateFormat.format(new Date()) + " 时运行");
		} else if (scheduleJob.getIsInfo().equals("2")) {

			systemInfoSocketHandler().sendMessageToAllUsers(
					"任务名称 = [" + scheduleJob.getName() + "]" + " 在 " + dateFormat.format(new Date()) + " 时运行");
		}

		run();

		System.out.println("任务名称 = [" + scheduleJob.getName() + "]" + " 在 " + dateFormat.format(new Date()) + " 时运行");
	}

	public abstract void run();

	private ApplicationContext getApplicationContext(JobExecutionContext context) throws Exception {
		ApplicationContext appCtx = null;
		appCtx = (ApplicationContext) context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
		if (appCtx == null) {
			throw new JobExecutionException("No application context available in scheduler context for key \""
					+ APPLICATION_CONTEXT_KEY + "\"");
		}
		return appCtx;
	}

	/**
	 *
	 * @return 
	 */
	public ApplicationContext getCxt() {
		return cxt;
	}

}
